package com.example.myapplication14_4;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.MediaController;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public class MainActivity extends AppCompatActivity {

    private VideoView videoView;
    private Button btnPlay, btnStop, btnSelectFile;
    private MediaController mediaController;
    private String currentVideoPath;
    private MediaPlayer mediaPlayer;
    private static final int PERMISSION_REQUEST_CODE = 1;
    private static final int FILE_SELECT_CODE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化视频播放器
        videoView = findViewById(R.id.videoView);

        // 初始化媒体播放器
        mediaPlayer = new MediaPlayer();

        // 初始化播放和停止按钮
        btnPlay = findViewById(R.id.btnPlay);
        btnStop = findViewById(R.id.btnStop);

        // 设置视频路径
        videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.testvideo);

        // 初始化静音开关
        Switch swMute = findViewById(R.id.swMute);
        swMute.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // 根据开关状态设置音量
                if (isChecked) {
                    mediaPlayer.setVolume(0, 0); // 静音
                } else {
                    mediaPlayer.setVolume(1, 1); // 恢复音量
                }
            }
        });

        // 初始化文件选择按钮
        btnSelectFile = findViewById(R.id.btnSelectFile);
        btnSelectFile.setOnClickListener(v -> checkPermissionAndSelectFile());

        // 设置默认视频路径
        currentVideoPath = "android.resource://" + getPackageName() + "/raw/testvideo";
        setupVideo(currentVideoPath);

        // 播放按钮点击事件
        btnPlay.setOnClickListener(v -> {
            if (videoView.isPlaying()) {
                videoView.pause();
                btnPlay.setText("播放");
            } else {
                videoView.start();
                btnPlay.setText("暂停");
            }
        });

        // 停止按钮点击事件
        btnStop.setOnClickListener(v -> {
            videoView.stopPlayback();
            setupVideo(currentVideoPath); // 重新设置视频源
            btnPlay.setText("播放");
        });
    }

    // 配置视频的方法
    private void setupVideo(String videoPath) {
        videoView.setVideoURI(Uri.parse(videoPath));
        videoView.setMediaController(null); // 重置控制器
        mediaController = new MediaController(this);
        videoView.setMediaController(mediaController);
        mediaController.setAnchorView(videoView);

        videoView.setOnPreparedListener(mp -> {
            mediaPlayer = mp;
            mp.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT);
            mp.setLooping(false); // 关闭循环播放
            if (!videoView.isPlaying()) {
                videoView.pause(); // 默认暂停
                btnPlay.setText("播放");
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (videoView.isPlaying()) {
            videoView.pause();
            btnPlay.setText("播放");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (videoView != null) {
            videoView.stopPlayback();
        }
    }

    private void checkPermissionAndSelectFile() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        } else {
            selectVideoFile();
        }
    }

    private void selectVideoFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "选择视频文件"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "请安装文件管理器", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                          @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                selectVideoFile();
            } else {
                Toast.makeText(this, "需要存储权限来选择视频文件", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    currentVideoPath = uri.toString();
                    setupVideo(currentVideoPath);
                }
            }
        }
    }
}